#!/bin/bash

#####################################################################
#                                                                   #
#          SmartKeyboard App Generator for iOS and Android          #
#               (c) Romain Michon CCRMA and Grame, 2016-2023        #
#                                                                   #
#####################################################################

. faustpath
. usage.sh

# change if you want to get the log of what's happening
LOG="/dev/null"

# exit if a command fails
set -e

# global option variables
LIB="0"
NVOICES=0
MIDI=0

echoHelp()
{
    echo "faust2teensy [-lib] [-midi] [-nvoices <num>] [Faust options (-vec -vs 8...)] <file.dsp>"
    option
    option -lib "generates a package containing an object compatible with the Teensy audio library (see https://github.com/grame-cncm/faust/tree/master-dev/architecture/teensy)"
    option -midi
    option "-nvoices <num>"
    option "Faust options"
    exit
}

if [ "$#" -eq 0 ]; then
    echo 'Please, provide a Faust file to process !'
    echo ''
    echoHelp
fi

###########################
# Processing Arguments
###########################

while [ $1 ]
do
    p=$1

    if [ $p = "-help" ] || [ $p = "-h" ]; then
        echoHelp
    elif [ $p = "-nvoices" ]; then
        shift
        NVOICES=$1
    elif [ $p = "-midi" ]; then
        MIDI=1
    elif [[ -f "$p" ]] && [ ${p: -4} == ".dsp" ]; then
        FILE="$p"
    elif [ $p = "-lib" ]; then
        LIB=1
    else
        OPTIONS="$OPTIONS $p"
    fi

shift

done

###########################
# Post Argument Processing
###########################

BASENAME=$(basename "$FILE")
MODULENAME="${BASENAME%.dsp}"

###########################
# Generating a lib package
###########################

if [ $LIB -eq 1 ]; then
    mkdir -p $MODULENAME
    faust $OPTIONS -uim -a $FAUSTARCH/teensy/teensy.cpp -i $FILE -o $MODULENAME/$MODULENAME.cpp
    if [ $NVOICES -gt 0 ]; then
        echo '#define NVOICES '$NVOICES >> $MODULENAME/$MODULENAME.h
    fi
    if [ $MIDI -eq 1 ]; then
        echo '#define MIDICTRL' >> $MODULENAME/$MODULENAME.h
    fi
    cat $FAUSTARCH/teensy/teensy.h >> $MODULENAME/$MODULENAME.h
    TMP=$(awk -v modName="$MODULENAME" '{gsub(/AudioFaust/,modName)}1' $MODULENAME/$MODULENAME.cpp)
    echo "$TMP" > $MODULENAME/$MODULENAME.cpp
    TMP=$(awk -v modName="$MODULENAME" '{gsub(/AudioFaust/,modName)}1' $MODULENAME/$MODULENAME.h)
    echo "$TMP" > $MODULENAME/$MODULENAME.h
    TMP=$(awk -v modName="$MODULENAME.h" '{gsub(/teensy.h/,modName)}1' $MODULENAME/$MODULENAME.cpp)
    echo "$TMP" > $MODULENAME/$MODULENAME.cpp
    TMP=$(awk -v modName="faust_$MODULENAME" '{gsub(/faust_teensy/,modName)}1' $MODULENAME/$MODULENAME.h)
    echo "$TMP" > $MODULENAME/$MODULENAME.h

    zip -r $MODULENAME.zip $MODULENAME > $LOG
    rm -r $MODULENAME
fi
